package fr.uniscol.siecle.parsers;

import java.io.File;
import java.util.Iterator;

import org.jdom2.Document;
import org.jdom2.Element;

import fr.uniscol.siecle.model.Division;
import fr.uniscol.siecle.model.FichierSIECLE;
import fr.uniscol.siecle.model.Groupe;
import fr.uniscol.siecle.model.MEF;
import fr.uniscol.siecle.model.Structures;

public class FichierSIECLEStructuresParser extends IFichierSIECLEParser {

	@Override
	public FichierSIECLE buildModel(Document doc, ParsingResults results) {
		
		Structures model = new Structures();
		
		Element eDonnees = doc.getRootElement().getChild("DONNEES");
		Element eDivisions = eDonnees.getChild("DIVISIONS");
		Element eGroupes = eDonnees.getChild("GROUPES");
		
		Iterator<Element> ite = eDivisions.getChildren().iterator();
		Iterator<Element> ita = null;
		Iterator<Element> itd = null;
		
		Element eDiv = null, eGrp = null;
		Element eMefA = null;
		Element eMef = null;
		Division div = null;
		Groupe grp = null;
		MEF mef = null;
		
		while(ite.hasNext()){
			eDiv = ite.next();
			
			div = new Division();
			div.setCode(eDiv.getAttributeValue("CODE_STRUCTURE"));
			div.setLibelle_long(eDiv.getChildText("LIBELLE_LONG"));
			div.setCode_rne(eDiv.getChildText("CODE_RNE"));
			
			eMefA = eDiv.getChild("MEFS_APPARTENANCE");
			ita = eMefA.getChildren().iterator();
			while(ita.hasNext()){
				eMef = ita.next();
				
				mef = new MEF();
				mef.setCode(eMef.getChildText("CODE_MEF"));
				
				div.getMefsAppartenance().add(mef);
			}
			
			model.getDivisions().add(div);
		}
		
		ite = eGroupes.getChildren().iterator();
		while(ite.hasNext()){
			eGrp = ite.next();
			
			grp = new Groupe();
			grp.setCode(eGrp.getAttributeValue("CODE_STRUCTURE"));
			grp.setLibelle_long(eGrp.getChildText("LIBELLE_LONG"));
			grp.setCode_rne(eGrp.getChildText("CODE_RNE"));
			
			eMefA = eGrp.getChild("MEFS_APPARTENANCE");
			ita = eMefA.getChildren().iterator();
			while(ita.hasNext()){
				eMef = ita.next();
				
				mef = new MEF();
				mef.setCode(eMef.getChildText("CODE_MEF"));
				
				grp.getMefsAppartenance().add(mef);
			}
			
			eDivisions = eGrp.getChild("DIVISIONS_APPARTENANCE");
			itd = eDivisions.getChildren().iterator();
			while(itd.hasNext()){
				eDiv = itd.next();
				
				div = model.findDivision(eDiv.getChildText("CODE_STRUCTURE"));
				
				if(div != null){
					grp.getDivisionsAppartenances().add(div);
				}
			}
			
			model.getGroupes().add(grp);
		}
		
		return model;
	}
}
